package com.rimi.cs.javaweb.service.impl;

import com.rimi.cs.javaweb.dao.CartMapper;
import com.rimi.cs.javaweb.dao.MobileMapper;
import com.rimi.cs.javaweb.pojo.Cart;
import com.rimi.cs.javaweb.pojo.Mobile;
import com.rimi.cs.javaweb.pojo.User;
import com.rimi.cs.javaweb.service.ICartService;
import com.rimi.cs.javaweb.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 购物车服务实现类
 *
 * @author Hayes
 * @date 2018-06-27 14:47
 */
@Service
public class CartServiceImpl implements ICartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private MobileMapper mobileMapper;

    @Override
    public boolean inseret(Long phoneId, Long quantity,HttpServletRequest request) {
        Cart cart = new Cart();
        User user = (User) request.getSession().getAttribute(Constant.USER_INFO);
        cart.setUserid(user.getUserid());
        cart.setQuantity(quantity);
        cart.setPhoneid(phoneId);
        return cartMapper.insert(cart) > 0;
    }

    @Override
    public List<Cart> selectByUserId(HttpServletRequest request) {
        // 根据用户ID查询购物车条目
        User user = (User) request.getSession().getAttribute(Constant.USER_INFO);
        List<Cart> cartList = cartMapper.selectByUserId(user.getUserid());
        request.getSession().setAttribute("cartList",cartList);

        Double total = 0.0;
        for (Cart cart : cartList) {
            Mobile mobile = mobileMapper.selectByPrimaryKey(cart.getPhoneid());
            total = total + mobile.getPrice().floatValue() * cart.getQuantity();
            cart.setMobile(mobile);
        }
        request.getSession().setAttribute("cartItemsTotal",total);
        return cartList;
    }

    @Override
    public int cartItemCount(HttpServletRequest request) {
        int size = selectByUserId(request).size();
        return size;
    }

    @Override
    public boolean deleteItem(Long id) {
        int i = cartMapper.deleteByPrimaryKey(id);
        return i > 0;
    }

    @Override
    public boolean updateItem(Long id, Long quantity) {
        return cartMapper.updateByItemCount(id,quantity) > 0;
    }

    @Override
    public boolean selectByID(Long id) {
        Cart cart = cartMapper.selectByPrimaryKey(id);
        return cart != null;
    }

    @Override
    public Cart selectByUidAndPid(Long userId,Long phoneId) {
        Cart cart = cartMapper.selectByUidAndPid(userId,phoneId);
        return cart;
    }

    @Override
    public int deleteByUserId(Long userId) {
        return cartMapper.deleteByUserID(userId);
    }

}
